package com.squareup.picasso;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.StatFs;
import android.provider.Settings;

import com.squareup.picasso.BitmapHunter.CompressFormat;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.List;

public final class Utils {
    static final String THREAD_PREFIX = "Picasso-";

    static final Charset US_ASCII = Charset.forName("US-ASCII");
    private static StringBuilder b = new StringBuilder();
    private static final byte[] c = new byte[]{71, 73, 70, 56, 55, 97};
    private static final byte[] d = new byte[]{71, 73, 70, 56, 57, 97};
    private static final byte[] e = new byte[]{-1, -40, -1};
    private static final byte[] f = new byte[]{-119, 80, 78, 71, 13, 10, 26, 10};

    static void closeQuietly(InputStream arg1) {
        if (arg1 != null) {
            try {
                arg1.close();
            } catch (IOException v0) {
            }
        }
    }

    static <T> T checkNotNull(T arg1, String arg2) {
        if (arg1 == null) {
            throw new NullPointerException(arg2);
        }

        return arg1;
    }

    public static void checkMain() {
        boolean isMain = Looper.getMainLooper().getThread() == Thread.currentThread();
        if (!isMain) {
            throw new IllegalStateException("Method call should happen from the main thread.");
        }
    }

    public static String createKey(Request arg3) {
        String v0 = Utils.createKey(arg3, Utils.b);
        Utils.b.setLength(0);
        return v0;
    }

    static File createDefaultCacheDir(Context context) {
        File cache = new File(context.getApplicationContext().getCacheDir(), "picasso-cache");
        if (!cache.exists()) {
            cache.mkdirs();
        }
        return cache;
    }

    static long calculateDiskCacheSize(File dir) {
        long cacheSize;
        try {
            StatFs statFs = new StatFs(dir.getAbsolutePath());
            cacheSize = (long) statFs.getBlockSize() * (long) statFs.getBlockCount() / 50;
        } catch (IllegalArgumentException v0) {
            cacheSize = 5242880L;
        }
        return Math.max(Math.min(cacheSize, 52428800), 5242880L);
    }

    static String createKey(Request data, StringBuilder stringBuilder) {
        char v2 = 'x';
        char v3 = '\n';
        if (data.stableKey != null) {
            stringBuilder.ensureCapacity(data.stableKey.length() + 50);
            stringBuilder.append(data.stableKey);
        } else if (data.uri != null) {
            String v0 = data.uri.toString();
            stringBuilder.ensureCapacity(v0.length() + 50);
            stringBuilder.append(v0);
        } else {
            stringBuilder.ensureCapacity(50);
            stringBuilder.append(data.resourceId);
        }

        stringBuilder.append(v3);
        if (data.rotationDegrees != 0f) {
            stringBuilder.append("rotation:").append(data.rotationDegrees);
            if (data.hasRotationPivot) {
                stringBuilder.append('@').append(data.rotationPivotX).append(v2).append(data.rotationPivotY);
            }

            stringBuilder.append(v3);
        }

        if (data.hasSize()) {
            stringBuilder.append("resize:").append(data.targetWidth).append(v2).append(data.targetHeight);
            stringBuilder.append(v3);
        }

        if (data.centerCrop) {
            stringBuilder.append("centerCrop\n");
        } else if (data.centerInside) {
            stringBuilder.append("centerInside\n");
        }

        if (data.transformations != null) {
            int v2_1 = data.transformations.size();
            int v1;
            for (v1 = 0; v1 < v2_1; ++v1) {
                stringBuilder.append(data.transformations.get(v1).key());
                stringBuilder.append(v3);
            }
        }

        return stringBuilder.toString();
    }

    static Resources getResources(Context context, Request request) throws FileNotFoundException {
        if (request.resourceId != 0 || request.uri == null) {
            return context.getResources();
        } else {
            String pkg = request.uri.getAuthority();
            if (pkg == null) {
                throw new FileNotFoundException("No package provided: " + request.uri);
            } else {
                try {
                    return context.getPackageManager().getResourcesForApplication(pkg);
                } catch (PackageManager.NameNotFoundException e) {
                    throw new FileNotFoundException("Unable to obtain resources for package: " + request.uri);
                }
            }
        }
    }

    static int getResourceId(Resources resources, Request data) throws FileNotFoundException {
        int v0_1;
        if (data.resourceId != 0 || data.uri == null) {
            return data.resourceId;
        } else {
            String pkg = data.uri.getAuthority();
            if (pkg == null) {
                throw new FileNotFoundException("No package provided: " + data.uri);
            } else {
                List<String> segments = data.uri.getPathSegments();
                if (segments != null && !segments.isEmpty()) {
                    if (segments.size() == 1) {
                        try {
                            return Integer.parseInt(segments.get(0));
                        } catch (NumberFormatException e) {
                            throw new FileNotFoundException("Last path segment is not a resource ID: " + data.uri);
                        }
                    } else if (segments.size() == 2) {
                        return resources.getIdentifier(segments.get(1), segments.get(0), pkg);
                    } else {
                        throw new FileNotFoundException("More than two path segments: " + data.uri);
                    }
                }

                throw new FileNotFoundException("No path segments: " + data.uri);
            }
        }
    }

    static void flushStackLocalLeaks(Looper looper) {
        Handler handler = new Handler(looper) {
            @Override
            public final void handleMessage(Message msg) {
                sendMessageDelayed(this.obtainMessage(), 1000);
            }
        };
        handler.sendMessageDelayed(handler.obtainMessage(), 1000);
    }

    static int getBitmapBytes(Bitmap arg3) {
        int v0 = arg3.getByteCount();
        if (v0 < 0) {
            throw new IllegalStateException("Negative size: " + arg3);
        }

        return v0;
    }

    static Object getSystemService(Context context, String name) {
        return context.getSystemService(name);
    }

    static void closeQuietly(Closeable closeable) {
        try {
            closeable.close();
        } catch (Exception v0) {
        }
    }

    private static boolean a(byte[] arg5, byte[] arg6) {
        boolean v1 = false;
        if (arg6 != null) {
            int v0 = 0;
            while (true) {
                if (v0 >= arg6.length) {
                    break;
                } else if (arg5[v0] == arg6[v0]) {
                    ++v0;
                    continue;
                }

                return v1;
            }

            v1 = true;
        }

        return v1;
    }

    static byte[] b(InputStream arg4) throws IOException {
        ByteArrayOutputStream v0 = new ByteArrayOutputStream();
        byte[] v1 = new byte[4096];
        while (true) {
            int v3 = arg4.read(v1);
            if (-1 == v3) {
                break;
            }

            v0.write(v1, 0, v3);
        }

        return v0.toByteArray();
    }

    static Downloader createDefaultDownloader() {
        return new Downloader();
    }

    static int calculateMemoryCacheSize(Context context) {
        return ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getLargeMemoryClass() * 1048576 / 7;
    }

    static boolean hasPermission(Context context, String permission) {
        return context.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
    }

    public static CompressFormat c(InputStream arg8) {
        int v1 = 0;
        CompressFormat v0 = null;
        int v2 = 12;
        try {
            byte[] v2_1 = new byte[v2];
            arg8.read(v2_1, 0, 12);
            if ((Utils.a(v2_1, Utils.d)) || (Utils.a(v2_1, Utils.c))) {
                return CompressFormat.GIF;
            }

            if (Utils.a(v2_1, Utils.e)) {
                return CompressFormat.JPEG;
            }

            if (Utils.a(v2_1, Utils.f)) {
                return CompressFormat.PNG;
            }

            if (("RIFF".equals(new String(v2_1, 0, 4, "US-ASCII"))) && ("WEBP".equals(new String(v2_1, 8, 4, "US-ASCII")))) {
                v1 = 1;
            }

            if (v1 == 0) {
                return v0;
            }

            v0 = CompressFormat.WEBP;
        } catch (Exception v1_1) {
        }

        return v0;
    }

    @TargetApi(value = 9)
    public static long c(File arg2) {
        long v0_1;
        try {
            v0_1 = arg2.getUsableSpace();
        } catch (Throwable v0) {
            v0.printStackTrace();
            v0_1 = -1;
        }
        return v0_1;
    }

    static boolean isAirplaneModeOn(Context context) {
        ContentResolver contentResolver = context.getContentResolver();
        try {
            if (Settings.System.getInt(contentResolver, "airplane_mode_on", 0) == 0) {
                return false;
            }
        } catch (NullPointerException e) {
            return false;
        }

        return true;
    }

    /**
     * Deletes the contents of {@code dir}. Throws an IOException if any file
     * could not be deleted, or if {@code dir} is not a readable directory.
     */
    static void deleteContents(File dir) throws IOException {
        File[] files = dir.listFiles();
        if (files == null) {
            throw new IOException("not a readable directory: " + dir);
        }
        for (File file : files) {
            if (file.isDirectory()) {
                deleteContents(file);
            }
            if (!file.delete()) {
                throw new IOException("failed to delete file: " + file);
            }
        }
    }

    static String readFully(Reader reader) throws IOException {
        try {
            StringWriter writer = new StringWriter();
            char[] buffer = new char[1024];
            int count;
            while ((count = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, count);
            }
            return writer.toString();
        } finally {
            reader.close();
        }
    }
}

